<template>
  <div>
    <el-form class="login-content-form"
             :model="ruleForm"
             :rules="rules"
             ref="accountForm">
      <el-form-item class="login-animation-one">
        <el-input type="text"
                  placeholder="请输入用户名"
                  v-model="ruleForm.userName"
                  clearable
                  autocomplete="off"
                  size="large">
          <template #prefix>
            <el-icon class="el-input__icon">
              <elementUser/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation-two" prop="password">
        <el-input :type="isShowPassword ? 'text' : 'password'"
                  placeholder="请输入密码"
                  v-model="ruleForm.password"
                  autocomplete="off"
                  size="large">
          <template #prefix>
            <el-icon class="el-input__icon">
              <elementUnlock/>
            </el-icon>
          </template>
          <template #suffix>
            <i class="iconfont el-input__icon login-content-password"
               :class="isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
               @click="isShowPassword = !isShowPassword">
            </i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation-three" prop="code">
        <el-row :gutter="15">
          <el-col :span="14">
            <el-input type="text"
                      maxlength="4"
                      placeholder="请输入验证码"
                      v-model="ruleForm.code"
                      clearable
                      autocomplete="off"
                      size="large">
            </el-input>
          </el-col>
          <el-col :span="9">
            <div class="login-content-code">
              <Sidentify :identifyCode="identifyCode"
                         ref="verifyRef"
                         v-model="vueCode"/>
            </div>
            <template #prefix>
              <el-icon class="el-input__icon">
                <elementPosition/>
              </el-icon>
            </template>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item class="login-animation-four">
        <el-button type="primary"
                   class="login-content-submit"
                   round
                   @click="onSignIn"
                   :loading="loading.signIn">
          <span>{{ $t("message.account.accountBtnText") }}</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {
  toRefs,
  reactive,
  defineComponent,
  computed,
  getCurrentInstance,
  ref,
} from "vue";
import Sidentify from "/@/components/verificationCode/index.vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";
import {initFrontEndControlRoutes} from "/@/router/frontEnd";
import {initBackEndControlRoutes} from "/@/router/backEnd";
import {dynamicRoutes, roleHome} from "/@/router/route";
import {useStore} from "/@/store/index";
import {Session} from "/@/utils/storage";
import {formatAxis} from "/@/utils/formatTime";
import {signIn} from "/@/api/login/index";
import {getDataTime} from "/@/api/app";
import {encrypt} from "/@/components/wigem/crypto";

import request from "/@/utils/request";

export default defineComponent({
  name: "loginAccount",
  components: {
    Sidentify,
  },
  setup() {
    const verifyRef = ref(null);
    const accountForm = ref();
    const {t} = useI18n();
    const {proxy} = getCurrentInstance() as any;
    const store = useStore();
    const route = useRoute();
    const router = useRouter();
    const validatorCode = (rule, value, callback) => {
      if (verifyRef.value.imgCode.toLowerCase() === value.toLowerCase()) {
        callback();
      } else {
        callback(new Error("验证码错误"));
      }
    };
    const state = reactive({
      vueCode: "",
      isShowPassword: false,
      userInfos: {},
      ruleForm: {
        userName: "",
        password: "",
        code: "",
      },
      loading: {
        signIn: false,
      },
      rules: {
        code: [{validator: validatorCode, trigger: "blur"}],
      },
      upDataPassword: false,
    });

    // 时间获取
    const currentTime = computed(() => {
      return formatAxis(new Date());
    });
    // 登录
    const onSignIn = async () => {
      let valid = await proxy.$refs.accountForm.validate();
      if (valid) {
        state.loading.signIn = true;
        signIn({
          userName: state.ruleForm.userName,
          password: encrypt(state.ruleForm.password),
        }).then((res) => {
          if (!res.success) {
            ElMessage.error(res.msg);
            state.loading.signIn = false;
            return;
          }
          //判断是否需要修改密码
          // if (isOverMonth(res.data.updateTime)) {
          //   proxy.$wigem.alert.warning("请定期修改您的密码以保证账户安全!!!");
          //   setTimeout(() => {
          //     proxy.$emit("password-dialog", true);
          //   }, 400);
          //   return;
          // }

          const user = res.data;
          const userInfos = {
            userName: user.realName,
            userId: user.userId,
            photo: "/images/user_head.jpeg",
            time: new Date().getTime(),
            roles: ["common1"],
            authBtnList: ["search", "downLoad", "refresh"],
            adminMark: user.adminMark,
            homeCode: user.roleList[0].homeUrl,
            roleName: user.roleList[0].roleName
          };
          dynamicRoutes[0].name = userInfos.homeCode;
          dynamicRoutes[0].redirect = roleHome[userInfos.homeCode];
          //   存储 token 到浏览器缓存
          Session.set("token", user.token);
          // 存储用户信息到浏览器缓存
          Session.set("userInfo", userInfos);
          Session.set("userName", user.userName);
          Session.set("type", true);
          // 1、请注意执行顺序(存储用户信息到vuex)
          store.dispatch("userInfos/setUserInfos", userInfos);

          initBackEndControlRoutes();
          signInSuccess();
        }).catch((res) => {
          ElMessage.error(res.msg);
          state.loading.signIn = false;
        });
      }
    };

    //请求报告期
    async function getCurrentReport() {
      try {
        const response = await request({
          url: "/api/approve/report/query/current/reportId",
          method: "get",
        });
        await store.dispatch("reportData/setCurrentReport", response.data);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    }

    //判断
    const isOverMonth = (dateStr) => {
      var targetDate = new Date(dateStr);
      var targetTimestamp = targetDate.getTime();
      var currentTimestamp = new Date().getTime();
      var diffDays = Math.floor(
          (currentTimestamp - targetTimestamp) / (24 * 60 * 60 * 1000)
      );
      return diffDays > 90;
    };

    // 登录成功后的跳转
    const signInSuccess = async () => {
      // 初始化登录成功时间问候语
      let currentTimeInfo = currentTime.value;
      let userInfo = Session.get("userInfo");
      console.log(userInfo)
      setTimeout(() => {
        router.push({
          name: userInfo.homeCode,
        });
      }, 1500);
      // 关闭 loading
      state.loading.signIn = true;
      const signInText = t("message.signInText");
      ElMessage.success(`${currentTimeInfo}，${signInText}`);
      // 修复防止退出登录再进入界面时，需要刷新样式才生效的问题，初始化布局样式等(登录的时候触发，目前方案)
      proxy.mittBus.emit("onSignIn");
    };
    return {
      accountForm,
      verifyRef,
      currentTime,
      onSignIn,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  color: #000;
}

.login-content-form {
  margin-top: 10px;

  .login-animation-one,
  .login-animation-two,
  .login-animation-three,
  .login-animation-four,
  .login-animation-five {
    opacity: 0;
    animation-name: error-num;
    animation-duration: 0.5s;
    animation-fill-mode: forwards;
  }

  .login-animation-one {
    animation-delay: 0.1s;
  }

  .login-animation-two {
    animation-delay: 0.2s;
  }

  .login-animation-three {
    animation-delay: 0.3s;
  }

  .login-animation-four {
    animation-delay: 0.4s;
    margin-bottom: 5px;
  }

  .login-animation-five {
    animation-delay: 0.5s;
  }

  .login-content-password {
    display: inline-block;
    width: 25px;
    cursor: pointer;

    &:hover {
      color: #909399;
    }
  }

  .login-content-code {
    display: flex;
    align-items: center;
    justify-content: space-around;

    .login-content-code-img {
      width: 100%;
      height: 40px;
      line-height: 40px;
      background-color: #ffffff;
      border: 1px solid rgb(220, 223, 230);
      color: #333;
      font-size: 16px;
      font-weight: 700;
      letter-spacing: 5px;
      text-indent: 5px;
      text-align: center;
      cursor: pointer;
      transition: all ease 0.2s;
      border-radius: 4px;
      user-select: none;

      &:hover {
        border-color: #c0c4cc;
        transition: all ease 0.2s;
      }
    }
  }

  .login-content-submit {
    width: 100%;
    letter-spacing: 2px;
    font-weight: 300;
    margin-top: 15px;
  }
}
</style>
